package fit.conceptmap.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

import fit.conceptmap.dao.IShareDao;
import fit.conceptmap.entities.Conceptmap;
import fit.conceptmap.entities.Share;
import fit.conceptmap.entities.User;
import fit.conceptmap.utils.DrawUtils;

@Repository
public class ShareDaoImpl implements IShareDao {

	@PersistenceContext
	private EntityManager em;
	
	@Override
	public List<Share> getListShareByIdConcepMaps(String idConceptMaps) {
		TypedQuery<Share> query = em.createQuery(
				"Select p From Share p Where p.conceptmap.idConceptMaps = :idConceptMaps", 
				Share.class);
		query.setParameter("idConceptMaps", idConceptMaps);
		return query.getResultList();
	}

	@Override
	@Transactional
	public boolean share(String idConceptMaps, String idmember) {
		boolean result = true;
		try {
			Share share = new Share();
			Conceptmap conceptmap = em.find(Conceptmap.class, idConceptMaps);
			User member = em.find(User.class, idmember);
			share.setConceptmap(conceptmap);
			share.setUser(member);
			share.setIdshare(idConceptMaps + idmember + DrawUtils.random());
			em.persist(share);
		} catch (Exception e) {
			result = false;
		}
		return result;
	}

	@Override
	@Transactional
	public List<Conceptmap> getListShareByIdMember(String username) {
		TypedQuery<Share> query = em.createQuery(
				"Select p From Share p Where p.user.idUser = :username", 
				Share.class);
		query.setParameter("username", username);
		List<Share> listShare = query.getResultList();
		List<Conceptmap> result = new ArrayList<Conceptmap>();
		for (Share share : listShare) {
			Conceptmap concept = em.find(Conceptmap.class, share.getConceptmap().getIdConceptMaps());
			result.add(concept);
		}
		return result;
	}

}
